package com.cartitem.action;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.cartitem.bean.CartItem;
import com.cartitem.service.ICartItemService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Controller("cartItemAction")
@Scope("prototype")
public class CartItemAction extends ActionSupport {

	public void setCartItemService(ICartItemService cartItemService) {
		this.cartItemService = cartItemService;
	}

	public String getAmount() {
		return amount;
	}

	public void setAmount(String amount) {
		this.amount = amount;
	}

	public String getBookid() {
		return bookid;
	}

	public void setBookid(String bookid) {
		this.bookid = bookid;
	}

	public String saveCartItem() {
		CartItem newItem = createCartItem();
		CartItem oldItem = cartItemService.getCartByUsernameAndBookid(newItem.getCart_id(), newItem.getBook_id());
		if (oldItem == null) {
			cartItemService.addCartItem(newItem);
		} else {
			oldItem.setAmount(oldItem.getAmount() + 1);
			cartItemService.updateCartItem(oldItem);
		}
		return SUCCESS;
	}
	
	public String updateCartItem() {
		CartItem item = createCartItem();
		cartItemService.updateCartItem(item);
		return SUCCESS;
	}
	
	private CartItem createCartItem() {
		System.out.println("bookid: " + bookid + ", amount: " + amount);
		CartItem item = new CartItem();
		String name = (String) ActionContext.getContext().getSession().get("user");
		item.setCart_id(name);
		item.setBook_id(bookid);
		item.setAmount(Integer.parseInt(amount));
		item.setCreate_date(new Date());
		System.out.println(item);
		return item;
	}

	private static final long serialVersionUID = 7868834130679499329L;

	private String bookid;
	private String amount;

	@Autowired
	private ICartItemService cartItemService;
}
